package com.quicks.beauty.server.web;

import com.quicks.beauty.core.entity.WxUser;
import com.quicks.beauty.core.utils.UUIDGenerator;
import com.quicks.beauty.core.vo.UserBillVO;
import com.quicks.beauty.server.common.AjaxResult;
import com.quicks.beauty.server.config.QiNiuConfig;
import com.quicks.beauty.server.service.RedisBillService;
import com.quicks.beauty.server.service.UploadService;
import com.quicks.beauty.server.service.UserBillService;
import com.quicks.beauty.server.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping(value = "bill")
@Api(tags = "消费凭证兑换")
public class BillPicController extends BaseController {


    protected final Logger logger = LoggerFactory.getLogger(BillPicController.class);

    @Autowired
    private AtomicInteger atomicInteger;

    @Autowired
    private QiNiuConfig qiNiuConfig;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserBillService billService;

    @Autowired
    private RedisBillService redisBillService;

    /**
     * 上传消费凭证
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "上传消费凭证")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "上传用户ID，", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "file", value = "上传文件，", paramType = "query", required = true, dataType = "File")
    })
    public AjaxResult upload(HttpServletRequest request) throws IOException {
        AjaxResult results = null;
        try {
            results = new AjaxResult();
            String userId = request.getParameter("userId");
            if (StringUtils.isEmpty(userId)) {
                AjaxResult failure = AjaxResult.failure("userId为空");
                return failure;
            }
            WxUser user = userService.getUserById(userId);
            if (user == null) {
                AjaxResult failure = AjaxResult.failure("userId不存在");
                return failure;
            }
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = multipartRequest.getFile("file");
            logger.info("上传文件开始,fileName:{}", file.getOriginalFilename());
            String fileType = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
//            String fullPath = "india/" + generateFileName(fileType);
            String fullPath = "quickLove/" + generateFileName(fileType);
            uploadService.asyncUpload(fullPath, file.getInputStream());
            String billId = UUIDGenerator.generate();
            int bill = billService.insertBill(userId, qiNiuConfig.getDomainHost() + fullPath, billId);
            if (bill == 10) {
                results.setSuccess(false);
                results.setMsg("亲,每日最大上传次数10次!");
            } else {
                results.setSuccess(true);
                redisBillService.pushUserBillById(userId, billId);
            }

        } catch (Exception e) {
            results = new AjaxResult();
            logger.error("上传那文件接口异常,e:{}", e);
            results.setSuccess(false);
            results.setMsg("服务器打盹中...");
        }
        return results;
    }

    public String generateFileName(String fileType) {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        StringBuilder sb = new StringBuilder();
        sb.append(year);
        sb.append("/");
        sb.append(calendar.get(Calendar.MONTH) + 1);
        sb.append("/");
        sb.append(calendar.get(Calendar.DAY_OF_MONTH));
        sb.append("-");
        sb.append(calendar.get(Calendar.HOUR_OF_DAY));// 1位
        sb.append(calendar.get(Calendar.MINUTE));// 1位
        sb.append(calendar.get(Calendar.SECOND));// 1位
        sb.append("-");
        sb.append(atomicInteger.getAndIncrement());
        sb.append(RandomStringUtils.randomAlphanumeric(6));
        sb.append(".");
        sb.append(fileType);
        return sb.toString();
    }


    /**
     * 我的凭证兑换记录
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "我的凭证兑换记录")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "上传用户ID，", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页面，", paramType = "query", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "数量，", paramType = "query", required = true, dataType = "Integer")
    })
    public AjaxResult getUserBills(@RequestParam("userId") String userId,
                                   @RequestParam("pageNum") Integer pageNum,
                                   @RequestParam("pageSize") Integer pageSize) {
        AjaxResult result = new AjaxResult();
        pageSize = pageSize == null ? super.pageSize : pageSize;
        pageNum = pageNum == null ? super.pageNum : pageNum;
        try {
            List<UserBillVO> billVOS = billService.getUserBillVOs(userId, pageNum, pageSize);
            result.setData(billVOS);
            result.setSuccess(true);
            boolean userbill = redisBillService.delUserBillId(userId);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("系统错误,稍后再试");
            e.printStackTrace();
        }
        return result;
    }

    @ApiOperation(value = "是否有兑换订单")
    @RequestMapping(value = "has", method = RequestMethod.GET)
    public AjaxResult hasUserBill(@RequestParam("userId") String userId) {
        AjaxResult result = new AjaxResult();
        boolean userbill = redisBillService.getUserbill(userId);
        if (userbill) {
            result.setSuccess(true);
        } else {
            result.setSuccess(false);
        }
        return result;
    }


}
